/**
 * Mock 服务器配置
 * 拦截 HTTP 请求并返回模拟数据
 */

import Mock from 'mockjs'

export interface MockConfig {
  url: string | RegExp
  method: 'GET' | 'POST' | 'PUT' | 'DELETE'
  response: (options: any) => any
  timeout?: number
}

/**
 * 设置 Mock 服务器
 */
export function setupMockServer(mocks: MockConfig[]) {
  // 设置全局延迟
  Mock.setup({
    timeout: '200-600' // 模拟网络延迟
  })

  // 注册所有 Mock 接口
  mocks.forEach(mock => {
    Mock.mock(mock.url, mock.method.toLowerCase(), mock.response)
  })

  // 拦截 XMLHttpRequest
  const originalXHR = window.XMLHttpRequest
  const originalFetch = window.fetch

  // 恢复原始请求的方法
  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  Mock.XHR.prototype.send = function() {
    if (this.custom.xhr) {
      this.custom.xhr.withCredentials = this.withCredentials || false
    }
    this.proxy_send(...arguments)
  }

  console.log(`🎭 已注册 ${mocks.length} 个 Mock 接口`)
}